import { useState, useEffect } from 'react';
import { AppstoreOutlined, PieChartOutlined, SettingOutlined } from '@ant-design/icons';
import type { MenuProps } from 'antd';
import { Menu } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
type MenuItem = Required<MenuProps>['items'][number];

const menus: MenuItem[] = [
    {
        key: '/app/index',
        icon: <AppstoreOutlined />,
        label: '首页',
    },
    {
        key: '/app/example',
        icon: <PieChartOutlined />,
        label: '示例',
        children: [
            {
                key: '/app/example/demoA',
                label: 'keep-alive的页面',
            },
            {
                key: '/app/example/demoB',
                label: '普通页面',
            },
        ],
    },
    {
        key: '/app/完全不存在的地址',
        icon: <SettingOutlined />,
        label: '404',
    },
];

const MainMenu = () => {
    const navigateTo = useNavigate();

    let { pathname } = useLocation();
    const [openKeys, setOpenKeys] = useState(['/app/dataMgmt']);
    const [defaultSelectedKeys, setDefaultSelectedKeys] = useState('');

    useEffect(() => {
        let pathnameArr = pathname.split('/');
        if (pathnameArr.length > 3) {
            pathnameArr = pathnameArr.slice(0, 3);
        }
        setOpenKeys([pathnameArr.join('/')]);

        setDefaultSelectedKeys(pathname);
    }, [pathname]);

    const changeMenu = (e: { key: string }) => {
        navigateTo(e.key);
    };

    const onOpenChange = (keys: string[]) => {
        setOpenKeys([keys[keys.length - 1]]);
    };

    return (
        <Menu
            openKeys={openKeys}
            theme="dark"
            selectedKeys={[defaultSelectedKeys]}
            mode="inline"
            items={menus}
            onClick={changeMenu}
            onOpenChange={onOpenChange}
        />
    );
};

export default MainMenu;
